package com.dwy2002.product.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwy2002.common.exception.EmptyIdException;
import com.dwy2002.pojo.po.product.ProductCategory;
import com.dwy2002.product.mapper.ProductCategoryMapper;
import com.dwy2002.product.service.IProductCategoryService;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.dwy2002.common.utils.Utils.*;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/02/17
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements IProductCategoryService {

    /**
     * 保存商品与分类之间的关系
     *
     * @param productId  商品id
     * @param categoryId 分类id
     * @return true：插入成功，false：插入失败
     * @author 杜伟毅
     * @since 2025/2/18 0018 23:36
     */
    @Override
    public Boolean saveProductToCategory(String productId, String categoryId) {
        if (isEmptyOrNull(productId) || isEmptyOrNull(categoryId)) throw new EmptyIdException("saveProductToCategory");

        ProductCategory productCategory = new ProductCategory();
        productCategory.setProductId(productId);
        productCategory.setCategoryId(categoryId);
        return save(productCategory);
    }

    /**
     * 根据分类id获取分类id
     *
     * @param categoryId 分类id
     * @return 返回商品id集合
     * @author 杜伟毅
     * @since 2025/3/2 0002 13:33
     */
    @Override
    public List<String> getProductIdByCategoryId(String categoryId) {
        LambdaQueryWrapper<ProductCategory> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ProductCategory::getCategoryId, categoryId);
        List<ProductCategory> productCategories = list(lqw);
        return productCategories.stream()
                .map(ProductCategory::getProductId)
                .toList();
    }

    /**
     * 根据分类id删除商品与分类关系
     *
     * @param categoryId 分类id
     * @author 杜伟毅
     * @since 2025/3/2 0002 14:00
     */
    @Override
    public void deleteProductToCategory(String categoryId) {
        validateIdNotEmpty(categoryId, "deleteProductToCategory");

        remove(new LambdaQueryWrapper<ProductCategory>()
                .eq(ProductCategory::getCategoryId, categoryId));
    }

    /**
     * 根据商品id删除商品与分类关系
     *
     * @param productIds 商品id集合
     * @author 杜伟毅
     * @since 2025/3/2 0002 17:19
     */
    @Override
    public void deleteProductCategoryByProductId(List<String> productIds) {
        if (isListEmpty(productIds)) throw new EmptyIdException("deleteProductCategoryByProductId");

        remove(new LambdaQueryWrapper<ProductCategory>().in(ProductCategory::getProductId, productIds));
    }
}